import os
import json

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from chatbot.chat import ChatBotGraph
from onecup.settings import BASE_DIR
from chatbot.preprocess_data import Question


def chat(request):
    ctx = ""
    sql = ""
    s1 = ""
    s2 = ""
    f = ""
    begin = ""
    end = ""
    if request.POST:
        sent = request.POST['question_post']
        ctx = ChatBotGraph.chat_main(sent)[0]
        s1 = ChatBotGraph.chat_main(sent)[1]
        f = json.dumps(s1, ensure_ascii=False)
        begin = f.find('MATCH')
        end = f.rfind('return')
        s2 = f[begin:end]
        sql = s2 + ' return *'
    return render(request, "chatbot/chat.html", {"ctx": ctx, "sql": sql})


def upload_file(request):
    return render(request, 'chatbot/uploadfile.html')


def opbot(request):
    return render(request, 'chatbot/opbot.html')


def dialogue(request):
    sentence = request.POST.get("sentence")
    print(sentence)
    try:
        que = Question()
        answer = que.question_process(sentence)
    except Exception as e:
        print(e)
        answer = "我也还不知道呢！"
    if not answer:
        answer = "我不知道！"
    print(answer)
    return JsonResponse(answer, safe=False)


def upload(request):
    if request.method == "POST":  # 请求方法为POST时，进行处理
        myFile = request.FILES.get("myfile")  # 获取上传的文件，如果没有文件，则默认为None
        print(myFile)
        if not myFile:
            msg = '没有文件上传'
            return render(request, 'chatbot/uploadfile.html', {'msg': msg})
        destination = open(os.path.join(BASE_DIR, 'chatbot/upload', myFile.name), 'wb+')  # 打开特定的文件进行二进制的写操作
        for chunk in myFile.chunks():  # 分块写入文件
            destination.write(chunk)
        destination.close()
        msg = '文件上传成功'
        return render(request, 'chatbot/study.html', {'msg': msg})


def study(request):
    if request.method == "POST":
        # 执行task任务
        x = os.system('python3 /python/ansibleUI/scripts/study.py')
        return render(request, 'chatbot/study_success.html')


def download(request):
    file = open(os.path.join(BASE_DIR, 'chatbot/download', '1.csv'), 'rb')
    response = HttpResponse(file)
    response['Content-Type'] = 'application/octet-stream'  # 设置头信息，告诉浏览器这是个文件
    response['Content-Disposition'] = 'attachment;filename="1.csv"'
    return response

